#include<stdio.h>
#include<stdlib.h>
#include<string.h>

// @ 结构体嵌套二级指针
struct Teacher{
    char * name;
    char ** students;
};


struct Teacher ** allocateSpace(){
    struct Teacher ** p = malloc(sizeof(struct Teacher *) * 3);

    for(int i=0;i<3;i++){
       p[i] = malloc(sizeof(struct Teacher));
       p[i]->name = malloc(sizeof(char)*64);
       sprintf(p[i]->name,"teacher_%d",i+1);

       // 给学生数组分配内存
       p[i]->students = malloc(sizeof(char *)* 4); 
       //给学生的姓名开辟内存
       for(int j=0;j<4;j++){
           p[i]->students[j] = malloc(sizeof(char)*64);
           sprintf(p[i]->students[j],"%s_student_%d", p[i]->name, j+1);
       }
    }


    return p;
}

void printArr(struct Teacher **p){
    if (p == NULL){
        return;
    }

    for(int i=0;i<3;i++){
        printf("Teacher:%s \t", p[i]->name);
        for(int j=0;j<4;j++){
            printf("Stundet:%s \t",p[i]->students[j]);
        }
        printf("\n");
    }
}

// 释放内存
void freeSpace(struct Teacher ** p){
    if (p==NULL){
        return ;
    }
    for(int i=0;i<3;i++){
        for(int j=0;j<4;j++){
            if(p[i]->students[j]!=NULL){
                free(p[i]->students[j]);
                p[i]->students[j] = NULL;
            }       
        }
        if(p[i]->students !=NULL){
            free(p[i]->students);
        }
        
       if(p[i]->name!=NULL){
            free(p[i]->name);
       }

       if(p[i] !=NULL){
           free(p[i]);
       }
        
    }
    free(p);
    p =NULL;
}

void test(){
    struct Teacher ** p = NULL;
    p = allocateSpace();

    // 打印
    printArr(p);

    // 释放内存
    freeSpace(p);
    p = NULL;
}

void main(){

    test();

}